<template>
  <div class="app-container">
    <cus-wraper>
      <cus-filter-wraper>
        <el-form ref="elForm" :model="formData" :rules="rules" size="small" label-width="100px" :disabled="disabled">
          <el-tabs v-model="formData.activeName">
            <el-tab-pane label="作业基本信息" name="JobInfo">
              <el-form-item label="所属项目" prop="applicationId" label-width="100px">
                <el-select v-model="formData.applicationId" placeholder="请选择所属项目" style="width: 800px"
                           @change="appChange" :disabled="appDisabled">
                  <el-option v-for="item in formData.applicationList" :key="item.id" :label="item.name"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="作业名称" prop="jobName">
                <el-input v-model="formData.jobName" placeholder="请输入作业名称" clearable style="width: 800px"/>
              </el-form-item>
              <el-form-item label="处理类型" prop="flinkType">
                <el-select v-model="formData.flinkType" placeholder="请选择文件类型" style="width: 800px">
                  <el-option label="流处理" value="streaming"/>
                </el-select>
              </el-form-item>
              <el-form-item label="flink jar" prop="flinkJarId" label-width="100px">
                <el-select v-model="formData.flinkJarId" placeholder="请选择jar" style="width: 800px" @change="jarChange">
                  <el-option v-for="item in formData.jarList" :key="item.id" :label="item.fileName"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="jar路径" prop="jarPath">
                <el-input v-model="formData.jarPath" placeholder="请输入作业名称" clearable style="width: 800px" readonly/>
              </el-form-item>
              <el-form-item label="main入口" prop="mainClass">
                <el-input v-model="formData.mainClass" placeholder="请输入作业名称" clearable style="width: 800px"/>
              </el-form-item>
              <el-form-item label="执行模式" prop="deployModel" label-width="100px">
                <el-select v-model="formData.deployModel" placeholder="请选择执行模式">
                  <el-option label="yarn-application" value="yarn-application"/>
                  <el-option label="yarn-per-job" value="yarn-per-job" disabled/>
                  <el-option label="yarn-session" value="yarn-session" disabled/>
                </el-select>
              </el-form-item>
              <!--              <el-form-item label="备注" prop="remark">-->
              <!--                <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" style="width: 800px"-->
              <!--                          :autosize="{minRows: 4, maxRows: 4}"></el-input>-->
              <!--              </el-form-item>-->

            </el-tab-pane>
            <el-tab-pane label="配置信息" name="jobConf">
              <el-divider content-position="left">基础配置</el-divider>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="Parallelism" prop="parallelism">
                    <el-input-number v-model="formData.parallelism" :min="1" style="width: 300px">
                    </el-input-number>
                    <el-tooltip placement="top" style="margin-left: 5px">
                      <div slot="content">
                        默认并发数
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="Resolve Order" prop="resolveOrder" label-width="120px">
                    <el-select v-model="formData.resolveOrder" placeholder="请选择执行模式" style="width: 300px">
                      <el-option label="parent-first" value="parent-first"></el-option>
                      <el-option label="child-first" value="child-first"></el-option>
                    </el-select>

                    <el-tooltip placement="top" style="margin-left: 5px">
                      <div slot="content">
                        类加载方式
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="jobMem" prop="jobManagerMem">
                    <el-input v-model="formData.jobManagerMem" style="width: 300px">
                      <template slot="append">MB</template>
                    </el-input>
                    <el-tooltip placement="top" style="margin-left: 5px">
                      <div slot="content">
                        jobManager的内存
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="taskMem" prop="taskManagerMem" label-width="120px">
                    <el-input v-model="formData.taskManagerMem" style="width: 300px">
                      <template slot="append">MB</template>
                    </el-input>
                    <el-tooltip placement="top" style="margin-left: 5px">
                      <div slot="content">
                        taskManager的内存
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="SlotNum" prop="slotNum">
                    <el-input-number v-model="formData.slotNum" :min="1" style="width: 300px">
                    </el-input-number>
                    <el-tooltip placement="top" style="margin-left: 5px">
                      <div slot="content">
                        taskmanager槽位数
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </el-form-item>
                </el-col>
              </el-row>


              <!--flink 高级参数-->
              <el-divider content-position="left">Flink高级配置</el-divider>
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="addConf('flinkConf')">添加Flink其他配置
              </el-button>
              <el-table ref="dragTable" :data="formData.flinkAdvConfTmp" row-key="columnId" :max-height="tableHeight"
                        style="margin-top: 5px">
                <el-table-column label="KEY" min-width="300px">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.key" size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="VALUE" min-width="300px">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.value" size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click.native.prevent="deleteConf(scope.$index, formData.flinkAdvConfTmp)"
                    >删除
                    </el-button>
                  </template>
                </el-table-column>

              </el-table>

              <!--flink main参数-->
              <el-divider content-position="left">Main参数</el-divider>
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="addConf('argsConf')">添加Main参数
              </el-button>
              <el-table ref="dragTable" :data="formData.argsConfTmp" row-key="columnId" :max-height="tableHeight"
                        style="margin-top: 5px">
                <el-table-column label="KEY" min-width="300px">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.key" size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="VALUE" min-width="300px">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.value" size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click.native.prevent="deleteConf(scope.$index, formData.argsConfTmp)"
                    >删除
                    </el-button>
                  </template>
                </el-table-column>

              </el-table>

              <!--jvm 参数-->
              <el-divider content-position="left">JVM参数</el-divider>
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="addConf('jvmConf')">添加JVM参数</el-button>
              <el-table ref="dragTable" :data="formData.jvmConfTmp" row-key="columnId" :max-height="tableHeight"
                        style="margin-top: 5px">
                <el-table-column label="KEY" min-width="300px">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.key" size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="VALUE" min-width="300px">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.value" size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click.native.prevent="deleteConf(scope.$index, formData.jvmConfTmp)"
                    >删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>


              <!--yarn 基础参数-->
              <el-divider content-position="left" v-if="formData.deployModel==='yarn-application'||formData.deployModel==='yarn-per-job'
              ||formData.deployModel==='yarn-session'">yarn基础配置
              </el-divider>
              <el-row :gutter="20" v-if="formData.deployModel==='yarn-application'||formData.deployModel==='yarn-per-job'
              ||formData.deployModel==='yarn-session'">
                <el-col :span="8">
                  <el-form-item label="yarnAppType" label-width="120px">
                    <el-input v-model="formData.yarnApplicationType" placeholder="请输入yarn应用类型" clearable
                              style="width: 300px"/>
                    <el-tooltip placement="top" style="margin-left: 5px">
                      <div slot="content">
                        yarn应用类型
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="yarnAppName" label-width="120px">
                    <el-input v-model="formData.yarnApplicationName" placeholder="请输入yarn应用名称" clearable
                              style="width: 300px"/>
                    <el-tooltip placement="top" style="margin-left: 5px">
                      <div slot="content">
                        yarn应用名称
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="yarnQueue">
                    <el-input v-model="formData.yarnQueueName" placeholder="请输入yarn队列名称" clearable
                              style="width: 300px"/>
                    <el-tooltip placement="top" style="margin-left: 5px">
                      <div slot="content">
                        yarn队列名称
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" v-if="formData.deployModel==='yarn-application'||formData.deployModel==='yarn-per-job'
              ||formData.deployModel==='yarn-session'">
                <el-col :span="8">
                  <el-form-item label="yarnJobMem" prop="yarnJobManagerMem" label-width="120px">
                    <el-input v-model="formData.yarnJobManagerMem" style="width: 300px">
                      <template slot="append">MB</template>
                    </el-input>
                    <el-tooltip placement="top" style="margin-left: 5px">
                      <div slot="content">
                        yarn的jobmanager内存
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="yarnTaskMem" prop="yarnTaskManagerMem" label-width="120px">
                    <el-input v-model="formData.yarnTaskManagerMem" style="width: 300px">
                      <template slot="append">MB</template>
                    </el-input>
                    <el-tooltip placement="top" style="margin-left: 5px">
                      <div slot="content">
                        yarn的taskmanager内存
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="yarnSlotNum">
                    <el-input-number v-model="formData.yarnSlotNum" :min="0" style="width: 300px">
                    </el-input-number>
                    <el-tooltip placement="top" style="margin-left: 5px">
                      <div slot="content">
                        yarn的task槽位数
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </el-form-item>
                </el-col>

              </el-row>

              <!--yarn的高级参数-->
              <el-divider content-position="left" v-if="formData.deployModel==='yarn-application'||formData.deployModel==='yarn-per-job'
              ||formData.deployModel==='yarn-session'">Yarn高级配置
              </el-divider>
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="addConf('yarnConf')" v-if="formData.deployModel==='yarn-application'||formData.deployModel==='yarn-per-job'
              ||formData.deployModel==='yarn-session'">添加Yarn其他配置
              </el-button>
              <el-table ref="dragTable" :data="formData.yarnAdvConfTmp" row-key="columnId" :max-height="tableHeight"
                        style="margin-top: 5px"
                        v-if="formData.deployModel==='yarn-application'||formData.deployModel==='yarn-per-job'
              ||formData.deployModel==='yarn-session'">
                <el-table-column label="KEY" min-width="300px">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.key" size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="VALUE" min-width="300px">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.value" size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click.native.prevent="deleteConf(scope.$index, formData.yarnAdvConfTmp)"
                    >删除
                    </el-button>
                  </template>
                </el-table-column>

              </el-table>

              <!--日志配置-->
              <el-divider content-position="left">日志配置</el-divider>
              <div class="code-container" ref="container">
                <slot></slot>
              </div>

            </el-tab-pane>
            <el-tab-pane label="依赖信息" name="jobDep">
              <el-tabs v-model="formData.depTapName" type="card">
                <el-tab-pane label="POM" name="pom">
                  <div class="pom-container" ref="pomContainer">
                    <slot></slot>
                  </div>

                  <div style="margin-top: 25px">
                    <el-button type="primary" size="mini" @click="apply">应用</el-button>
                  </div>

                </el-tab-pane>
                <el-tab-pane label="UPLOAD JAR" name="upload">
                  <el-upload
                      class="upload-demo"
                      ref="uploadJarFile"
                      drag
                      multiple
                      accept=".jar"
                      :file-list="fileList"
                      :show-file-list="true"
                      :auto-upload="false"
                      :on-remove="handelRemove"
                      :before-upload="beforeUpload"
                      :on-change="fileChange"
                      :http-request="HttpUploadPost"
                      action="">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传jar文件</div>
                  </el-upload>
                  <el-button size="small" type="primary" @click="uploadSummit" style="margin-top: 10px"
                             :loading="isUpload">立即上传
                  </el-button>
                </el-tab-pane>
              </el-tabs>
              <div style="horiz-align: left;margin-top: 25px">
                <el-tag>当前的第三方依赖列表:</el-tag>
                <el-table
                    :data="formData.dependenciesList"
                    style="width: 100%"
                    max-height="250" @row-click="depRowClick">
                  <el-table-column label="名称" prop="name" align="center" min-width="100"></el-table-column>
                  <el-table-column label="类型" prop="type" align="center" min-width="200">
                    <template slot-scope="scope">
                      <el-tag v-if="scope.row.type==='pom'" type="success">maveny依赖</el-tag>
                      <el-tag v-else type="warning">上传的jar</el-tag>
                    </template>
                  </el-table-column>

                  <el-table-column label="maven" prop="data" align="center" min-width="200">
                    <template slot-scope="scope">
                     <span>
                       {{
                         getPomStr(scope.row)
                       }}
                     </span>
                    </template>
                  </el-table-column>

                  <el-table-column label="临时地址" prop="data" align="center" min-width="200">
                    <template slot-scope="scope">
                     <span>
                       {{ getPath(scope.row) }}
                     </span>
                    </template>
                  </el-table-column>

                  <el-table-column
                      fixed="right"
                      label="操作"
                      width="120">
                    <template slot-scope="scope">
                      <el-button
                          @click.native.prevent="deleteDepRow(scope.$index, formData.dependenciesList)"
                          type="text"
                          size="small">
                        移除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

            </el-tab-pane>
          </el-tabs>
          <el-form-item style="text-align: center;margin-left:-100px;margin-top:10px;">
            <el-button type="primary" :loading="isSave" @click="doSave">保存</el-button>
            <el-button @click="handelBack">返回</el-button>
          </el-form-item>
        </el-form>
      </cus-filter-wraper>
    </cus-wraper>
  </div>
</template>

<script>
import axios from 'axios'
import * as monaco from "monaco-editor";
import {getAppList} from "@/api/resource/application";
import {getJarListByAppId, getDefaultLog, addJarmanagement} from "@/api/resource/jarmanagement"
import {toPomString} from './Pom'
import {getToken} from "@/utils/auth";
import {deleteHdfsTmp, addJob, getFlinkConfByJobId} from "@/api/resource/job";


export default {

  name: "flinkTask",
  components: {},
  props: {},
  data() {
    return {
      disabled: false,
      tableHeight: null,
      appDisabled: false,
      isUpload: false,
      isSave: false,
      //解析出来的依赖关系
      dependency: {
        pom: new Map(),
        jar: new Map()
      },
      editor: null,
      pomEditor: null,
      fileList: [],
      formData: {

        id: null,
        flinkJobId: '',
        activeName: 'JobInfo',
        depTapName: 'pom',
        applicationList: [],
        applicationId: null,
        jobName: '',
        flinkType: 'streaming',
        jarList: [],
        flinkJarId: '',
        jarPath: '',
        mainClass: '',
        deployModel: 'yarn-application',
        remark: '',
        jobType: 'flink',

        parallelism: 1,
        resolveOrder: 'parent-first',
        jobManagerMem: 1024,
        taskManagerMem: 1024,
        slotNum: 1,

        flinkAdvConfTmp: [],
        flinkAdvConf: '',

        argsConfTmp: [],
        argsConf: '',

        jvmConfTmp: [],
        jvmConf: '',

        yarnAdvConfTmp: [],
        yarnAdvConf: '',

        yarnApplicationType: '',
        yarnApplicationName: '',
        yarnQueueName: '',
        yarnJobManagerMem: '',
        yarnTaskManagerMem: '',
        yarnSlotNum: 0,

        dependenciesList: [],
        dependencies: '',

        logText: ''

      },
      rules: {
        applicationId: [{
          required: true,
          message: '所属项目不能为空',
          trigger: 'blur'
        }],
        jobName: [{
          required: true,
          message: '作业名称不能为空',
          trigger: 'blur'
        }],
        flinkType: [{
          required: true,
          message: '处理类型不能为空',
          trigger: 'blur'
        }],
        flinkJarId: [{
          required: true,
          message: 'jar包不能为空',
          trigger: 'blur'
        }],
        jarPath: [{
          required: true,
          message: 'jar路径不能为空',
          trigger: 'blur'
        }],
        mainClass: [{
          required: true,
          message: 'main入口不能为空',
          trigger: 'blur'
        }],
        deployModel: [{
          required: true,
          message: '发布模式不能为空',
          trigger: 'blur'
        }],
        slotNum: [{
          required: true,
          message: '槽位数不能为空',
          trigger: 'blur'
        }],
        parallelism: [{
          required: true,
          message: '并行度不能为空',
          trigger: 'blur'
        }],
        resolveOrder: [{
          required: true,
          message: '类加载方式不能为空',
          trigger: 'blur'
        }],

        jobManagerMem: [
          {required: true, message: 'jobmanager 内存不能为空', trigger: 'blur'},
          {pattern: /^[1-9]\d*$/, message: '请输入正确的格式,只能输入大于1的正整数'}
        ],

        taskManagerMem: [
          {required: true, message: 'taskmanager 内存不能为空', trigger: 'blur'},
          {pattern: /^[1-9]\d*$/, message: '请输入正确的格式,只能输入大于1的正整数'}
        ],

        yarnJobManagerMem: [
          {pattern: /^[1-9]\d*$/, message: '请输入正确的格式,只能输入大于1的正整数', required: false}
        ],

        yarnTaskManagerMem: [
          {pattern: /^[1-9]\d*$/, message: '请输入正确的格式,只能输入大于1的正整数', required: false}
        ],

      }
    }
  },
  methods: {


    isArrEmpty(arr) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].key === '' || arr[i].value === '') {
          return true;
        }
      }
      return false;
    },

    isRepeat(arr) {
      if (arr.length > 1) {
        for (let i = 0; i < arr.length; i++) {
          for (let j = i + 1; j < arr.length; j++) {
            if (arr[i].key === arr[j].key) {
              return true;
            }
          }
        }
      }
      return false;
    },

    getPomStr(data) {
      if (data.type === 'pom') {
        return toPomString(data.data)
      }
      return '';
    },
    getPath(data) {
      if (data.type !== 'pom') {
        return data.data.path
      }
      return ''
    },

    initEditor() {
      this.editor = monaco.editor.create(this.$refs.container, {
        value: getDefaultLog(), //                                                        代码
        readOnly: false, //                                                         只读
        language: 'xml', //                                                         语法
        theme: "vs-dark", //                                                        主题            vs/vs-dark/hc-black （可使用defineTheme中的主题）
        folding: true, //                                                           代码折叠
        position: true,
        showFoldingControls: "always",//                                            折叠图标显示     mouseover/always
        quickSuggestions: true, //                                                  支持搜索         ctrl + F
        automaticLayout: true, //                                                   resize自动布局
        cursorStyle: "line", //                                                     光标样式         line/block/underline/line-thin/block-outline/underline-thin
        roundedSelection: true, //                                                  控制选区是否有圆角
        fontSize: 15
      });

      this.pomEditor = monaco.editor.create(this.$refs.pomContainer, {
        value: '', //                                                        代码
        readOnly: false, //                                                         只读
        language: 'xml', //                                                         语法
        theme: "vs-dark", //                                                        主题            vs/vs-dark/hc-black （可使用defineTheme中的主题）
        folding: true, //                                                           代码折叠
        position: true,
        showFoldingControls: "always",//                                            折叠图标显示     mouseover/always
        quickSuggestions: true, //                                                  支持搜索         ctrl + F
        automaticLayout: true, //                                                   resize自动布局
        cursorStyle: "line", //                                                     光标样式         line/block/underline/line-thin/block-outline/underline-thin
        roundedSelection: true, //                                                  控制选区是否有圆角
        fontSize: 15
      });

    },

    getApplicationList() {
      getAppList().then(res => {
        this.formData.applicationList = res.rows
      })
    },

    /**
     * 选择项目发生改变
     * @param v
     */
    appChange(v) {
      this.getJarList(v);
    },

    getJarList(appId) {
      getJarListByAppId(appId).then(res => {
        this.formData.jarList = res.rows;
      })
    },

    /**
     * jar发生改变
     * @param v
     */
    jarChange(v) {
      const jar = this.formData.jarList.filter(jar => jar.id === v).at(0)
      this.formData.jarPath = jar.filePath;
      this.formData.mainClass = jar.mainClass;
    },
    addConf(type) {
      if (type === 'flinkConf') {
        this.formData.flinkAdvConfTmp.push({'key': '', 'value': ''})
      }
      if (type === 'argsConf') {
        this.formData.argsConfTmp.push({'key': '', 'value': ''})
      }
      if (type === 'jvmConf') {
        this.formData.jvmConfTmp.push({'key': '', 'value': ''})
      }
      if (type === 'yarnConf') {
        this.formData.yarnAdvConfTmp.push({'key': '', 'value': ''})
      }
    },

    deleteConf(index, rows) {
      rows.splice(index, 1);
    },

    apply() {
      const pom = this.pomEditor.getValue();
      if (pom === '') {
        return
      }
      const pomStr = pom.trimStart("\"").trimEnd("\"");
      const groupExp = /<groupId>([\s\S]*?)<\/groupId>/
      const artifactExp = /<artifactId>([\s\S]*?)<\/artifactId>/
      const versionExp = /<version>([\s\S]*?)<\/version>/
      const exclusionsExp = /<exclusions>([\s\S]*?)<\/exclusions>/
      pomStr.split('</dependency>').filter(x => x.replace(/\\s+/, '') !== '').forEach(dep => {
        const groupId = dep.match(groupExp) ? (groupExp.exec(dep)[1]).trim() : null
        const artifactId = dep.match(artifactExp) ? (artifactExp.exec(dep)[1]).trim() : null
        const version = dep.match(versionExp) ? (versionExp.exec(dep)[1]).trim() : null
        const exclusion = dep.match(exclusionsExp) ? (exclusionsExp.exec(dep)[1]).trim() : null
        if (groupId != null && artifactId != null && version != null) {
          const id = groupId + '_' + artifactId
          const mvnPom = {
            'groupId': groupId,
            'artifactId': artifactId,
            'version': version
          }
          const pomExclusion = new Map()
          if (exclusion != null) {
            const exclusions = exclusion.split('<exclusion>')
            exclusions.forEach(e => {
              if (e != null && e.length > 0) {
                const e_group = e.match(groupExp) ? (groupExp.exec(e)[1]).trim() : null
                const e_artifact = e.match(artifactExp) ? (artifactExp.exec(e)[1]).trim() : null
                const id = e_group + '_' + e_artifact
                pomExclusion.set(id, {
                  'groupId': e_group,
                  'artifactId': e_artifact
                })
              }
            })
          }
          mvnPom.exclusions = pomExclusion
          console.log("解析之前的依赖列表：", this.formData.dependenciesList)
          this.dependency.pom.set(id, mvnPom)
        } else {
          console.error('dependency error...')
        }
      })
      this.updateDependency()
      this.pomEditor.setValue('');
    },
    updateDependency() {
      const deps = []
      const jars = []
      this.dependency.pom.forEach((v, k, item) => {
        if (v.exclusions) {
          const exclusions = []
          v.exclusions.forEach((e) => exclusions.push(e))
          v.exclusions = exclusions
        }
        deps.push(v)
      })
      this.dependency.jar.forEach((v, k, item) => {
        jars.push(v)
      })

      //列表中添加pom依赖
      deps.forEach(dep => {
        const name = dep.artifactId + "-" + dep.version + ".jar";
        const depId = dep.groupId + '_' + dep.artifactId
        const data = {
          "name": name,
          "type": "pom",
          "data": dep,
          "isSaved": false
        }
        if (this.formData.dependenciesList == null || this.formData.dependenciesList.length <= 0) {
          this.formData.dependenciesList.push(data)
        } else {

          let sameIndex = -1;
          this.formData.dependenciesList.find(function (item, index, arr) {
            const sameId = item.data.groupId + '_' + item.data.artifactId
            if (sameId === depId) {
              sameIndex = index;
            }
          })
          if (sameIndex !== -1) {
            this.formData.dependenciesList.splice(sameIndex, 1);
          }
          this.formData.dependenciesList.push(data)
        }
      })
      console.log("解析之后的依赖列表：", this.formData.dependenciesList)
      //列表中添加上传的jar
      // this.pomList=deps;
      this.jarList = jars;

    },

    /**
     * 移除
     * @param index
     * @param rows
     */
    deleteDepRow(index, rows) {
      const data = rows[index]
      console.log("移除的数据：" + rows[index])
      rows.splice(index, 1);
      if (data.type === 'pom') {
        //移除pom依赖
        const currentId = data.data.groupId + '_' + data.data.artifactId
        this.dependency.pom.delete(currentId);
      } else {
        const params = [];
        params.push({"applicationId": this.formData.applicationId, "path": data.data.path});
        deleteHdfsTmp(params)
        if (this.formData.dependenciesList.filter(d => d.type !== 'pom').length <= 0) {
          this.appDisabled = false;
        }
      }

    },

    /**
     * 点击下边列表上边pom显示
     * @param row
     * @param event
     * @param column
     */
    depRowClick(row, event, column) {
      // if (row.type === 'pom') {
      //   this.pomEditor.setValue(toPomString(row.data))
      // }
    },

    handelRemove(file, fileList) {
      this.fileList = fileList;
    },


    beforeUpload(file) {
      let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (extension !== 'jar') {
        this.$message.warning('只能上传jar文件')
      }
    },

    fileChange(file, fileList) {
      if (this.fileList.length > 0) {
        let sameIndex = -1;
        for (let i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i].name === file.name) {
            sameIndex = i;
          }
        }
        if (sameIndex !== -1) {
          this.fileList.splice(sameIndex, 1);
          this.fileList.push(file)
        } else {
          this.fileList.push(file);
        }
      } else {
        this.fileList.push(file);
      }
      fileList = this.fileList
    },

    //执行上传
    HttpUploadPost(param) {
      if (this.formData.applicationId === '') {
        this.$message.warning('请先选择所属项目！')
        return;
      }
      if (this.fileList.length <= 0) return;
      let file_form = new FormData();
      this.fileList.forEach(f => {
        file_form.append("file", f.raw);
      })
      file_form.append("applicationId", this.formData.applicationId)
      this.fileList = [];
      this.isUpload = true;
      axios({
        url: process.env.VUE_APP_BASE_API + "/resource/job/createUploadFile", // 上传的图片服务器地址
        method: "POST",
        headers: {
          Authorization: "Bearer " + getToken()
        },
        data: file_form,
      }).then((res) => {
        this.isUpload = false;
        this.appDisabled = true;
        if (res.data.data.length > 0) {
          res.data.data.forEach(d => {
            const data = {
              "name": d.name,
              "type": "upload",
              "data": {"path": d.path, "isUpload": false},
              "isSaved": false
            }
            this.formData.dependenciesList.push(data)
          })

        }
      }).catch((err) => {
        this.isUpload = false;
        this.$notify.error({
          title: '错误',
          message: err
        });
      });
    },

    uploadSummit() {
      if (this.fileList !== undefined && this.fileList.length > 0) {
        let hasSame = false;
        if (this.formData.dependenciesList.length > 0) {
          this.formData.dependenciesList.forEach(d => {
            this.fileList.forEach(f => {
              if (f.name === d.name) {
                hasSame = true;
              }
            })
          })
        }
        if (hasSame) {
          this.$message.warning("依赖列表中存在相同的jar不允许上传！");
          return;
        }
        this.$refs.uploadJarFile.submit();
        this.fileList = [];
      } else {
        this.$message.warning("没有可上传的文件！");
        return false;
      }
    },


    clearData() {
      this.isUpload = false;
      this.appDisabled = false;
      this.isSave = false;

      this.dependency.pom.clear();
      this.dependency.jar.clear();

    },

    doSave() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) {
          this.$message.warning('请检查作业信息是否都填写！')
          return;
        }
        if (this.isUpload) {
          this.$message.warning('请等待依赖上传完成!')
          return;
        }

        if (this.formData.flinkAdvConfTmp.length > 0) {

          if (this.isArrEmpty(this.formData.flinkAdvConfTmp)) {
            this.$message.warning('配置的Key或者Value不能为空')
            return;
          }

          if (this.isRepeat(this.formData.flinkAdvConfTmp)) {
            this.$message.warning('存在相同的Key')
            return;
          }
          this.formData.flinkAdvConf = JSON.stringify(this.formData.flinkAdvConfTmp)
        }
        if (this.formData.argsConfTmp.length > 0) {

          if (this.isArrEmpty(this.formData.argsConfTmp)) {
            this.$message.warning('配置的Key或者Value不能为空')
            return;
          }
          if (this.isRepeat(this.formData.argsConfTmp)) {
            this.$message.warning('存在相同的Key')
            return;
          }
          this.formData.argsConf = JSON.stringify(this.formData.argsConfTmp)
        }


        if (this.formData.jvmConfTmp.length > 0) {

          if (this.isArrEmpty(this.formData.jvmConfTmp)) {
            this.$message.warning('配置的Key或者Value不能为空')
            return;
          }
          if (this.isRepeat(this.formData.jvmConfTmp)) {
            this.$message.warning('存在相同的Key')
            return;
          }
          this.formData.jvmConf = JSON.stringify(this.formData.jvmConfTmp)
        }

        if (this.formData.yarnAdvConfTmp.length > 0) {

          if (this.isArrEmpty(this.formData.yarnAdvConfTmp)) {
            this.$message.warning('配置的Key或者Value不能为空')
            return;
          }

          if (this.isRepeat(this.formData.yarnAdvConfTmp)) {
            this.$message.warning('存在相同的Key')
            return;
          }
          this.formData.yarnAdvConf = JSON.stringify(this.formData.yarnAdvConfTmp)
        }

        if (this.formData.dependenciesList.length > 0) {
          this.formData.dependencies = JSON.stringify(this.formData.dependenciesList)
        }
        this.formData.logText = this.editor.getValue();
        this.isSave = true;
        addJob(this.formData).then(res => {
          this.isSave = false;
          this.$message.success('保存成功！')
          const obj = {path: "/resource/job", query: {t: Date.now(), pageNum: this.$route.query.pageNum}};
          this.$tab.closeOpenPage(obj);
        }).catch(err => {
          this.isSave = false;
          this.$message.error(err)
        })

      })
    },

    initData() {
      this.tableHeight = document.documentElement.scrollHeight - 245 + "px"
      if (this.$route.query.data && this.$route.query.data.id) {
        if (this.$route.query.type === 'detail') {
          this.disabled = true;
        } else {
          this.disabled = false;
        }
        getAppList().then(res => {
          this.formData.applicationList = res.rows
          const data = this.$route.query.data;
          this.formData.flinkJobId = data.id;
          this.formData.applicationId = Number(data.applicationId);
          this.formData.jobName = data.jobName;
          this.formData.deployModel = data.deployModel;
          //获取jar
          this.getJarList(this.formData.applicationId);
          getFlinkConfByJobId(data.id).then(res => {
            this.formData.flinkJarId = Number(res.data.flinkJarId)
            this.formData.mainClass = res.data.mainClass;
            this.formData.jarPath = res.data.jarPath;
            this.formData.id = res.data.id;
            this.formData.remark = res.data.remark;
            this.formData.parallelism = res.data.parallelism;
            this.formData.resolveOrder = res.data.resolveOrder;
            this.formData.jobManagerMem = res.data.jobManagerMem;
            this.formData.taskManagerMem = res.data.taskManagerMem;
            this.formData.slotNum = res.data.slotNum;
            if (res.data.flinkAdvConf) {
              this.formData.flinkAdvConfTmp = JSON.parse(res.data.flinkAdvConf)
            }
            if (res.data.argsConf) {
              this.formData.argsConfTmp = JSON.parse(res.data.argsConf)
            }
            if (res.data.jvmConf) {
              this.formData.jvmConfTmp = JSON.parse(res.data.jvmConf)
            }
            if (res.data.yarnAdvConf) {
              this.formData.yarnAdvConfTmp = JSON.parse(res.data.yarnAdvConf)
            }
            this.formData.yarnApplicationType = res.data.yarnApplicationType;
            this.formData.yarnApplicationName = res.data.yarnApplicationName;
            this.formData.yarnQueueName = res.data.yarnQueueName;
            this.formData.yarnJobManagerMem = res.data.yarnJobManagerMem;
            this.formData.yarnTaskManagerMem = res.data.yarnTaskManagerMem;
            this.formData.yarnSlotNum = res.data.yarnSlotNum;
            this.editor.setValue(res.data.logText)
            if (res.data.dependencies) {
              this.formData.dependenciesList = JSON.parse(res.data.dependencies)
              if (this.formData.dependenciesList.filter(d => d.type !== 'pom').length > 0) {
                this.appDisabled = true;
              }
            }
          })
        })
      } else {
        this.getApplicationList();
      }
    },


    /**
     * 监听浏览器返回
     */
    goBack() {
      window.history.back();
      history.pushState(null, null, document.URL);
      const obj = {path: "/resource/job", query: {t: Date.now(), pageNum: this.$route.query.pageNum}};
      this.$tab.closeOpenPage(obj);
    },
    handelBack() {
      const obj = {path: "/resource/job", query: {t: Date.now(), pageNum: this.$route.query.pageNum}};
      this.$tab.closeOpenPage(obj);
    }
  },
  mounted() {
    this.initEditor()
    if (window.history && window.history.pushState) {
      history.pushState(null, null, document.URL);
      window.addEventListener('popstate', this.goBack, false);
    }
  },
  destroyed() {
    window.removeEventListener('popstate', this.goBack, false);
  },
  created() {
    this.initData()
  },
  watch: {
    '$route': ['initData', 'initEditor']
  }
}
</script>

<style>
.code-container {
  height: 100vh;
  overflow: hidden;
}


.pom-container {
  height: 350px;
  overflow: hidden;
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>